package com.jz.digital.base;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import org.jetbrains.annotations.NotNull;

import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.jz.digital.utils.DipPixelUtil;

import java.lang.reflect.Field;

/**
 * Copyright (c) 2019 深圳市爱都科技有限公司. All rights reserved.
 *
 * @Author: xyb
 * @CreateDate: 2019-12-11 17:22
 * @description
 */
public class BaseDialogFragment extends DialogFragment {
    private String mLanguage;
    private OnDismissionListener mOnDismissionListener;
    private OnShowingListener mOnShowingListener;

    private TextView tvTitle;
    private TextView tvSubtitle;

    public void setTitle(String title) {
        if (tvTitle != null) {
            tvTitle.setVisibility(View.VISIBLE);
            tvTitle.setText(title);
        }
    }

    public void setSubTitle(String subTitle) {
        if (tvSubtitle != null) {
            tvSubtitle.setVisibility(View.VISIBLE);
            tvSubtitle.setText(subTitle);
        }
    }

    @Nullable
    @Override
    public final View onCreateView(LayoutInflater inflater,
                                   @Nullable ViewGroup container,
                                   Bundle savedInstanceState) {

        if (getLayoutResId() == 0) {
            return super.onCreateView(inflater, container, savedInstanceState);
        } else {
            return inflater.inflate(getLayoutResId(), container, false);
        }
    }

    protected @LayoutRes
    int getLayoutResId() {
        return 0;
    }

    @Override
    public void onViewCreated(@NotNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 定义Dialog动画
        getDialog().getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
        initData();
        initUI(view);
        onThemeChange();
        initListener(view);
    }

    protected void initData() {
    }

    protected void initUI(View view) {
        if (getDialog() != null && getDialog().getWindow() != null) {
            Window window = getDialog().getWindow();
            window.getDecorView().setPadding(DipPixelUtil.dip2px(10), 0, DipPixelUtil.dip2px(10), DipPixelUtil.dip2px(15));// 宽度持平
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.gravity = Gravity.BOTTOM; // 紧贴底部
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;// 宽度持平
            window.setAttributes(lp);
        }
    }

    /**
     * 主题修改
     */
    protected void onThemeChange(){

    }

    protected void initListener(View view) {
    }

    /**
     * 当继承的子类使用系统自带的AlertDialog实现时,{@link #onViewCreated(View, Bundle)}方法会被忽略而不被执行.
     * 确保所有的子类都可以得到手机朝向改变的更新
     */
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getDialog().getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        if (mOnDismissionListener != null) {
            mOnDismissionListener.onDismission();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mOnShowingListener != null) {
            mOnShowingListener.onShowing();
        }
        //如果用户手动点击Home键或者电源键,再回来的时候,需要清除这个FLAG,否则用户点击屏幕外部Dialog不会消失
        if (getDialog().getWindow() != null) {
            getDialog().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
        }
    }


    public void show(FragmentManager fm) {
        try {
            if (fm.isDestroyed()) {
                return;
            }

            //避免重复显示Dialog
            String tag = getFragmentTag();
            if (tag != null && tag.equals(this.getClass().getSimpleName())) {
                // we do not show it twice
                if (fm.findFragmentByTag(tag) == null) {
                    super.show(fm, tag);
                }
            } else {
                super.show(fm, tag);
            }

            fm.executePendingTransactions();
            if (getDialog() != null && getDialog().getWindow() != null) {
                getDialog().getWindow().getDecorView().setSystemUiVisibility(
                        getActivity().getWindow().getDecorView().getSystemUiVisibility());

                // Make the dialogs window focusable again.
                getDialog().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showPressure(FragmentManager fm) {
        String tag = getFragmentTag();
        super.show(fm, tag);

    }

    /**
     * 界面隐藏弹窗
     *
     * @param manager
     * @param tag
     */
    public void showAllowingStateLoss(FragmentManager manager, String tag) {
        try {
            Field dismissed = DialogFragment.class.getDeclaredField("mDismissed");
            dismissed.setAccessible(true);
            dismissed.set(this, false);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        try {
            Field shown = DialogFragment.class.getDeclaredField("mShownByMe");
            shown.setAccessible(true);
            shown.set(this, true);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        FragmentTransaction ft = manager.beginTransaction();
        ft.add(this, tag);
        ft.commitAllowingStateLoss();
    }

    @Override
    public void dismiss() {
        if (getActivity() != null) {
            super.dismiss();
        }
    }

    @Override
    public void dismissAllowingStateLoss() {
        if (getActivity() != null) {
            super.dismissAllowingStateLoss();
        }
    }

    protected String getFragmentTag() {
        return this.getClass().getSimpleName();
    }

    public void setOnDismissionListener(OnDismissionListener listener) {
        mOnDismissionListener = listener;
    }

    public void setOnShowingListner(OnShowingListener listner) {
        this.mOnShowingListener = listner;
    }

    public interface OnDismissionListener {
        void onDismission();
    }

    public interface OnShowingListener {
        void onShowing();
    }

    public boolean isDialogShowing() {
        return getDialog() != null && getDialog().isShowing();
    }
}
